<?php

namespace backend\models;

use backend\traits\Singleton;
use frontend\tests\unit\models\ResetPasswordFormTest;
use Yii;
use yii\web\View;

/**
 * This is the model class for table "{{%admin_rule}}".
 *
 * @property int $id
 * @property int $pid
 * @property string $name
 * @property string $title
 * @property string $remark
 * @property string $icon
 * @property int $type 节点类型，1-控制器 | 0-方法
 * @property int $sort
 * @property int $status
 * @property int $isdelete
 */
class AdminRule extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%admin_rule}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['pid', 'type', 'sort', 'status', 'isdelete'], 'integer'],
            [['name', 'remark'], 'string', 'max' => 255],
            [['title'], 'string', 'max' => 50],
            [['icon'], 'string', 'max' => 64],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'pid' => 'Pid',
            'name' => 'Name',
            'title' => 'Title',
            'remark' => 'Remark',
            'level' => 'Level',
            'type' => 'Type',
            'sort' => 'Sort',
            'status' => 'Status',
            'isdelete' => 'Isdelete',
        ];
    }

    /**
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getData()
    {
        $query = self::find()
            ->select(['id', 'pid', 'title', 'name', 'sort', 'status', 'type', 'icon'])
            ->where(['isdelete' => 0])
            ->orderBy('sort ASC , id DESC');
        $data = $query->asArray()->all();

        return $data;
    }

    /**
     * @return array
     */
    public function getTreeData()
    {
        $data = $this->getData();
        $tree = [];
        $this->getNodeTree($data, $tree);

        return $this->getHtmlNode($tree);;
    }

    /**
     * @return array
     */
    public function getSelectData()
    {
        $data = $this->getTreeData();
        $firstNode = ['id' => '0', 'title' => '一级节点'];
        $selectData = $this->getSelectHtmlData($data);
        array_unshift($selectData, $firstNode);
        return $selectData;
    }

    /**
     * @param array $list
     * @param int $level
     * @return array
     */
    public function getSelectHtmlData(array $list, int $level = 0): array
    {
        static $select = [];
        foreach ($list as $k => $v) {
            if ($v['pid'] == 0) {
                $level = 0;
            }
            $select[] = ['id' => $v['id'], 'title' => ($level > 0 ? "|" : '') . str_repeat('--', $level) . $v['title']];
            if (isset($v['children'])) {
                $this->getSelectHtmlData($v['children'], ++$level);
            }
        }
        return $select;
    }

    /**
     * @param $list
     * @param $tree
     * @param int $pid
     */
    function getNodeTree(&$list, &$tree, int $pid = 0)
    {
        foreach ($list as $key => $value) {
            if ($pid == $value['pid']) {
                $tree[$value['id']] = $value;
                unset($list[$key]);
                $this->getNodeTree($list, $tree[$value['id']]['children'], $value['id']);
            }
        }
    }

    /**
     * @param $data
     * @return array
     */
    public function getHtmlNode(&$data)
    {
        foreach ($data as $key => &$val) {
            if (isset($val['children'])) {
                $val['children'] = array_values($val['children']);
                $this->getHtmlNode($val['children']);
            }
        }
        return array_values($data);
    }

    /**
     * @param $pid
     */
    public function setPid($pid)
    {
        $this->pid = empty($pid) ? 0 : $pid;
    }

    /**
     * 获取某一菜单所有父ID
     * @param $id
     * @return array
     */
    public function getAllPid($id)
    {
        static $pids = [];
        $row = AdminRule::find()->where(['id' => $id])->asArray()->one();
        if ($row['pid'] != 0) {
            $this->getAllPid($row['pid']);
            $pids[] = $row['pid'];
        }
        return $pids;
    }

    /**
     * 获取某一菜单所有父菜单名称
     * @param $id
     * @return array
     */
    public function getAllTitle($id)
    {
        static $names = [];
        $row = AdminRule::find()->where(['id' => $id])->asArray()->one();
        array_unshift($names, $row['title']);
        if ($row['pid'] != 0) {
            $this->getAllPid($row['pid']);
        }
        return $names;
    }

    /**
     * @param $id
     * @return false|string
     */
    public function setBreadcrumb()
    {
        $breadcrumb = '';
        $names = $this->getAllTitle(Yii::$app->view->params['activeId']);
        $breadcrumb = json_encode($names);
        Yii::$app->view->params['breadcrumb'] = $breadcrumb;
        return $breadcrumb;
    }

    /**
     * @return false|int|string|null
     */
    public function setActiveMenu()
    {
        //当前选中的菜单
        $pathInfo = Yii::$app->request->pathInfo ?: 'index';
        $pathInfo = trim($pathInfo, '/');
        $controller = explode('/', $pathInfo);
        $activeId = self::find()->select('id')
            ->where(['name' => '/' . $controller[0], 'type' => 1])
            ->orWhere(['name' => '/' . $controller[0] . '/index', 'type' => 1])
            ->asArray()->scalar();
        Yii::$app->view->params['activeId'] = $activeId;
        return $activeId;
    }

    public function filterMenu($ruleIds)
    {
        $rules = [];
        $ruleInfo = AdminRule::find()
            ->select('id,type,pid')
            ->where("id in ({$ruleIds})")
            ->asArray()->all();
        $pids = array_column($ruleInfo, 'pid');
        foreach ($ruleInfo as $val) {
            if ($val['type'] == 0 || ($val['type'] == 1 && !in_array($val['id'], $pids))) {
                $rules[] = $val['id'];
            }
        }
        return $rules;
    }
}
